package com.oly.cms.web.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson2.JSONObject;
import com.oly.cms.common.model.properties.OlyThemeConfigProperties;
import com.oly.cms.common.model.support.ThemeTreeNode;
import com.oly.cms.common.utils.ZipUtils;
import com.oly.cms.web.service.IWebThemeService;
import com.oly.cms.web.utils.WebUtils;
import com.grace.common.config.GraceConfig;
import com.grace.common.enums.GraceServerRoot;
import com.grace.common.exception.ServiceException;
import com.grace.common.exception.file.FileSizeLimitExceededException;
import com.grace.common.exception.file.InvalidExtensionException;
import com.grace.common.utils.StringUtils;
import com.grace.common.utils.file.FileUtils;
import com.grace.common.utils.file.MimeTypeUtils;
import com.grace.oss.service.impl.NativeOssHandler;

@Service
public class WebThemeServiceImpl implements IWebThemeService {

    @Autowired
    private NativeOssHandler ossHanded;

    @Override
    public boolean deleteThemeByName(String themeName) throws FileNotFoundException {

        return WebUtils.deleteThemeFile(themeName);
    }

    @Override
    public boolean uploadTheme(MultipartFile file, boolean cover)
            throws IOException, FileSizeLimitExceededException, InvalidExtensionException {
        String[] wt = FilenameUtils.getBaseName(file.getOriginalFilename()).split("_");
        String webName = "";
        String themeName = "";
        if (wt.length == 2) {
            webName = wt[0];
            themeName = wt[1];
        } else {
            throw new ServiceException("文件名规则错误!");
        }
        if (!GraceConfig.getOnlyCode().equals(webName)) {
            throw new ServiceException("服务编码不被允许,请确认后再进行安装!");
        }
        // 是否上传
        File already = Paths
                .get(GraceServerRoot.THEME_DIR.getWorkRoot(GraceServerRoot.THEME_TEMPLATE_DIR.getValue()), themeName)
                .toFile();
        if (already.exists() && !cover) {
            throw new ServiceException("主题已经上传,你选择的不是覆盖上传,主题安装终止!");
        }

        // xxx.xx
        String fileName = FilenameUtils.getName(file.getOriginalFilename());
        ossHanded.ossAppointUpload(file, GraceServerRoot.THEME_DIR, fileName, MimeTypeUtils.COMPRESS_EXTENSION);
        // 主题文件 路径/xx/themes/webName_themeName.zip
        File themeFile = Paths.get(GraceServerRoot.THEME_DIR.getWorkRoot(fileName)).toFile();
        // 解压到当前目录 themeFile.getParent() /themes
        ZipUtils.unZipFilesAppoint(themeFile.getAbsolutePath(), themeFile.getParent(), webName, themeName);
        // 删除压缩文件
        return ZipUtils.deleteDir(themeFile.getAbsoluteFile());
    }

    /**
     * 读取配置文件
     */
    @Override
    public Object selectThemeConfigSetting(String themeName) {
        File themeYaml = Paths
                .get(GraceServerRoot.THEME_DIR.getWorkRoot(GraceServerRoot.THEME_TEMPLATE_DIR.getValue()), themeName,
                        OlyThemeConfigProperties.THEME_INFO.defaultValue())
                .toFile();
        if (themeYaml.exists() && !themeYaml.isDirectory()) {
            YamlMapFactoryBean yamMap = new YamlMapFactoryBean();
            FileSystemResource fileResource = new FileSystemResource(themeYaml);
            yamMap.setResources(fileResource);
            return yamMap.getObject();
        } else {
            throw new ServiceException("获取主题说明异常");
        }
    }

    @Override
    public Object selectThemeConfigForm(String themeName) throws IOException {
        String jsonString = FileUtils.readFileContent(Paths
                .get(GraceServerRoot.THEME_DIR.getWorkRoot(GraceServerRoot.THEME_TEMPLATE_DIR.getValue()), themeName,
                        OlyThemeConfigProperties.THEME_CONFIG_FORM.defaultValue()));
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        return jsonObject;
    }

    @Override
    public List<ThemeTreeNode> selectThemeFileTree(String path) {
        if (StringUtils.isEmpty(path)) {
            path = "";
        }
        List<ThemeTreeNode> themeTreeNodes = new ArrayList<>();
        // 获取主题路径
        final File themesPath = new File(GraceServerRoot.THEME_DIR.getWorkRoot());
        listFile(themesPath, path, themeTreeNodes);
        return themeTreeNodes;

    }

    /**
     * 遍历主题文件
     * 
     * @param dir
     * @param prefix
     * @param themeList
     */
    private void listFile(File dir, String prefix, List<ThemeTreeNode> themeList) {
        File[] files = dir.listFiles();
        if (null != files) {
            for (File file : files) {
                ThemeTreeNode themeTreeNode = new ThemeTreeNode();
                themeTreeNode.setpId(prefix);
                themeTreeNode.setId(prefix + "/" + file.getName());
                themeTreeNode.setName(file.getName());
                if (file.isDirectory()) {
                    themeTreeNode.setParent(file.isDirectory());
                    themeTreeNode.setChildren(new ArrayList<>());
                    listFile(file, prefix + "/" + file.getName(), themeTreeNode.getChildren());
                }
                themeList.add(themeTreeNode);
            }
        }
    }

}
